package com.zjt.smart.mvp.presenter;

import com.zjt.smart.api.ApiManager;
import com.zjt.smart.api.BaiduApi;
import com.zjt.smart.api.server.BaseServer;
import com.zjt.smart.mvp.model.BaiduImageListBean;
import com.zjt.smart.mvp.presenter.base.BaseCallback;
import com.zjt.smart.mvp.presenter.base.LoadPresenter;
import com.zjt.smart.mvp.presenter.base.ResponseCallback;
import com.zjt.smart.mvp.view.LoadView;
import com.zjt.smart.util.CollectionUtil;
import com.zjt.smart.util.Json;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2017/11/3 0003 上午 11:07
 */

public class BaiduImageListPresenter extends LoadPresenter<BaiduImageListBean.DataBean>{

    private BaiduApi mApi;
    private BaseServer mServer;

    @Override
    protected void initAPI() {
        mApi = ApiManager.create(BaiduApi.class);
        mServer = ApiManager.getServer(BaiduApi.class);
    }

    public void loadImageList(LoadView<BaiduImageListBean.DataBean> loadView, boolean fromCache, int page, int size, String tag1, String tag2) {
        Call<ResponseBody> call =  mApi.loadImageList(page, size, tag1, tag2);
        doLoading(call, loadView, fromCache);
    }

    @Override
    protected BaseCallback createCallback(Call<ResponseBody> call, LoadView<BaiduImageListBean.DataBean> loadView) {
        return new ResponseCallback<BaiduImageListBean.DataBean>(call, loadView, mServer) {
            @Override
            protected List<BaiduImageListBean.DataBean> parseResult(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    return CollectionUtil.asList(Json.fromJson(jsonObject.getJSONArray("data").toString(), BaiduImageListBean.DataBean[].class));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
}
